<template>
  <div class="title">
    <div></div>
    <span>{{ securityObj?.label || '' }}数据</span>
  </div>

  <n-card v-for="(field, index) in fieldList" :bordered="false" :title="field.group">
    <template #header-extra>
      <n-button type="default" size="small" @click="onClearConfig(field)">清空</n-button>
    </template>
    <n-radio-group v-model:value="checkedData[field.unId]" :name="field.unId">
      <n-space>
        <template v-for="(config, idx) in field.children" :key="idx">
          <n-radio :value="config.unId" @click="onChange(config, field)">
            {{ config.label }}
          </n-radio>
        </template>
      </n-space>
    </n-radio-group>
    <!-- 实体数据权限回显 -->
    <div v-if="resultData && resultData[field.unId]?.fkFieldConfigData" class="config-extends">
      <div>指定数据</div>
      <n-checkbox-group :value="resultData[field.unId].fkFieldConfigData.split(',')">
        <n-space item-style="display: flex;">
          <template
            v-for="checkItem in resultData[field.unId].fkFieldConfigExtend"
            :key="checkItem.id"
          >
            <n-checkbox :value="checkItem.value" :label="checkItem.label" disabled></n-checkbox>
          </template>
        </n-space>
      </n-checkbox-group>
    </div>
    <!--    <p style="margin-top: 10px">-->
    <!--      <span style="font-weight: bolder">当前数据权限:</span>{{ resultData[field.fieldName]?.dataName }}-->
    <!--    </p>-->
  </n-card>
  <n-drawer></n-drawer>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import SysTbSecurityObjTree from './SysTbSecurityObjTree.vue';
  import httpApi from '@/views/AuthTbUser/UserBindDataSecurity/httpApi';
  import { Layer } from 'slash-layer';
  import SysTbSecurityTargetEntityTree from '@/views/AuthTbUser/UserBindDataSecurity/SysTbSecurityTargetEntityTree.vue';
  import { useThemeVars } from 'naive-ui';
  import { inject } from 'vue';
  import { Ref } from 'vue';
  import { reactive } from 'vue';

  export interface SysTbSecurityObjFieldResponse {
    fkFieldId: any;
    id: string;
    createTime: string;
    updateTime: string;
    createUserAccount: string;
    updateUserAccount: string;
    fkSecurityObjId: string;
    fieldName: string;
    fieldChinese: string;
    fieldConfig: any;
  }

  export default defineComponent({
    name: 'SysResourceMenuMange',
    components: { SysTbSecurityObjTree },
    props: {
      fkSecurityObjId: {},
      userId: {},
      isBatch: Boolean,
      securityObj: {},
    },
    setup(props) {
      const dataFieldMap = inject('dataFieldMap') as Ref<any>;
      const checkedData = ref<any>({});
      const resultData = ref<any>({});
      const themeVars = useThemeVars();
      const configExtend = ref<any>({});
      // 新旧选中项对比
      const oldConfigUnId = reactive<any>({});
      const newConfigUnId = reactive<any>({});
      const onChange = async (config: any, field: any) => {
        console.log('111', config, field);
        console.log(`${field.unId}`, resultData);
        // 判断是否是编辑状态
        let isEdit = false;
        newConfigUnId[field.unId] = config.unId;
        if (oldConfigUnId[field.unId] === newConfigUnId[field.unId]) {
          isEdit = true;
        } else {
          oldConfigUnId[field.unId] = newConfigUnId[field.unId];
          isEdit = false;
        }

        let tempDAta = {
          fkSecurityObjId: props.fkSecurityObjId,
          // fkSecurityObjName: field.fkSecurityObjName,
          fkFieldId: field.unId,
          fkFieldConfigId: config.unId,
          fkFieldConfigData: '',
          fkFieldConfigExp: config.value,
          // fkFieldName: field.fieldName,
          fkSecurityObjTableName: props.securityObj?.tableName || '',
          fkFieldConfigExtend: isEdit
            ? resultData.value[field.unId]?.fkFieldConfigExtend || []
            : [],
          fkSecurityObjTableClassName:config.fkSecurityObjTableClassName,
          securityType:config.type||'',
          securityEntityName:props.securityObj?.dataSecurityName||'',
          securityOptionName:config.label
        };
        if (config.type == 'IN') {
          console.log('abdc', tempDAta);
          const data: any[] = await Layer.localModal({
            position: 'sm',
            title: '选择指定数据',
            mask: true,
            content: {
              component: SysTbSecurityTargetEntityTree,
              props: {
                fieldName: field.fieldName,
                entityName: config.targetEntity,
                checkedIds: tempDAta?.fkFieldConfigExtend.map((config: { id: any }) => {
                  return config.id;
                }),
              },
            },
          });
          const fkFieldConfigData =
            data.map((d: { value: any }) => {
              return d.value;
            }) + '';
          tempDAta.fkFieldConfigData = fkFieldConfigData;
          tempDAta.fkFieldConfigExtend = data;
          configExtend.value[field.unId] = data;
        }
        if(config.type=='DYNAMIC')
        {
          tempDAta.fkFieldConfigData = config.valueTargetClass;

        }
        resultData.value[field.unId] = tempDAta;
        console.log('结果数据:{}', resultData);
      };
      const fieldList = ref<SysTbSecurityObjFieldResponse[]>([]);
      const reloadTable = async () => {
        // const msg = await httpApi.selectSysTbSecurityObjFieldPageList({
        //   fkSecurityObjId: props.fkSecurityObjId
        // })
        // 从map中取数据
        console.log('get', dataFieldMap.value.get(props.fkSecurityObjId));
        fieldList.value = dataFieldMap.value.get(props.fkSecurityObjId);
      };
      const doUpdate = () => {
        const updateData = [];
        for (let key in resultData.value) {
          updateData.push(resultData.value[key]);
        }
        console.log('提交数据{}', updateData);
        if (props.isBatch) {
          return httpApi.batchUserUpdate({
            userIdList: props.userId,
            fieldList: updateData,
          });
        } else {
          return httpApi.batchUpdateUserDataSecurity({
            userId: props.userId,
            fieldList: updateData,
          });
        }
      };
      const init = async () => {
        if (props.isBatch) return;
        const { data } = await httpApi.selectByUserId({ userId: props.userId });
        for (const d of data) {
          // 一个字段只能选一个权限
          checkedData.value[d.fkFieldId] = d.fkFieldConfigId;
          configExtend.value[d.fkFieldId] = d.fkFieldConfigExtend;
          resultData.value[d.fkFieldId] = d;
          oldConfigUnId[d.fkFieldId] = d.fkFieldConfigId;
        }
      };
      /** 清空该项配置 */
      function onClearConfig(field: any) {
        if (resultData.value[field.unId]) {
          delete resultData.value[field.unId];
        }
        checkedData.value[field.unId] = null;
      }
      onMounted(() => {
        init();
      });
      return {
        doUpdate,
        checkedData,
        fieldList,
        reloadTable,
        onChange,
        resultData,
        themeVars,
        configExtend,
        onClearConfig
      };
    },
  });
</script>

<style lang="less" scoped>
  .title {
    font-size: 18px;
    position: relative;
    > div {
      display: inline-block;
      width: 3px;
      height: 24px;
      background-color: v-bind('themeVars.primaryColor');
      margin-right: 4px;
      vertical-align: middle;
    }
  }
  .config-extends {
    margin-top: 8px;
  }
</style>
